package com.fulong.web;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
public class Captchaservlet {


    @GetMapping(value = "/getimg")
    public void makeImg(HttpServletRequest req , HttpServletResponse resp) throws IOException {
        int height = 20 ;
        int width  = 60 ;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics graphics = image.getGraphics();

        graphics.setColor(getRandColor());

        graphics.fillRect(0, 0, width, height);

        graphics.setColor(Color.WHITE);

        String yzm = "" ;

        for(int i = 1; i <= 4; i++ ){

            int number = new Random().nextInt(10);

            yzm += number;

            graphics.drawString(number + "" , 10 * i, 10);

        }
        HttpSession session = req.getSession();
        session.setAttribute("yzm" , yzm);
        resp.setContentType("image/png");
        ImageIO.write(image, "png", resp.getOutputStream());

    }

    private Color getRandColor() {
        int red = new Random().nextInt(255);
        int green = new Random().nextInt(255);
        int blue = new Random().nextInt(255);
        return new Color(red, green, blue);
    }
}
